package api

import (
	"beegoxiaomi/models"
	"encoding/json"

	"github.com/astaxie/beego"
)

type V1Controller struct {
	beego.Controller
}

func (c *V1Controller) Get() {
	c.Ctx.WriteString("ap1 v1")
}

//导航的api接口
func (c *V1Controller) Nav() {
	nav := []models.Nav{}
	models.DB.Find(&nav)
	c.Data["json"] = nav
	c.ServeJSON()
}

//执行登录 Post

// 1、copyrequestbody=true   1、c.Ctx.Input.RequestBody
func (c *V1Controller) DoLogin() {

	user := models.User{}
	data := c.Ctx.Input.RequestBody
	beego.Info(string(data))
	json.Unmarshal(data, &user)
	c.Data["json"] = map[string]interface{}{
		"phone":    user.Phone,
		"password": user.Password,
	}
	c.ServeJSON()
}

//修改 Put
type Article struct {
	Title string
}

func (c *V1Controller) DoEdit() {
	article := Article{}
	data := c.Ctx.Input.RequestBody
	beego.Info(string(data))
	json.Unmarshal(data, &article)

	c.Data["json"] = map[string]interface{}{
		"title":   article.Title,
		"success": true,
	}
	c.ServeJSON()
}

//删除数据
func (c *V1Controller) DeleteNav() {
	id, _ := c.GetInt("id")

	c.Data["json"] = map[string]interface{}{
		"id":      id,
		"message": "删除数据成功",
		"success": true,
	}
	c.ServeJSON()
}

//设置Session
func (c *V1Controller) SetUser() {
	c.SetSession("username", "张三")
	c.Data["json"] = map[string]interface{}{
		"message": "设置Session",
		"success": true,
	}
	c.ServeJSON()
}

//获取Session
func (c *V1Controller) GetUser() {
	username, ok := c.GetSession("username").(string)

	if ok {
		c.Data["json"] = map[string]interface{}{
			"username": username,
			"success":  true,
		}
	} else {
		c.Data["json"] = map[string]interface{}{
			"message": "获取session失败",
			"success": false,
		}
	}
	c.ServeJSON()
}
